package cn.b.sky.user.freemarker;

import cn.b.sky.common.constants.SystemConstant;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;
import freemarker.core.Environment;
import freemarker.template.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

public class ButtonDirective implements TemplateDirectiveModel {

  @SuppressWarnings("rawtypes")
  @Override
  public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
      throws TemplateException, IOException {
    // 检查参数是否传入
    if (params.isEmpty()) {
      throw new TemplateModelException("This directive have no parameters.");
    }

    if (loopVars.length != 0) {
      throw new TemplateModelException("This directive doesn't allow loop variables.");
    }
    // 真正开始处理输出内容  
    Writer out = env.getOut();
    //考虑到默认值，防止特别依赖数据库
    if (body != null) {
      String value = getBottonAuthContent(params);
      if (!StringUtils.isBlank(value)) {
        out.write(value);
      } else {
        body.render(out);
      }
    } else {
      out.write(getBottonAuthContent(params));
    }
  }

  private String getBottonAuthContent(Map<?, ?> params) {

    String menuCode = params.get("menuCode").toString();//权限的code
    if (SecurityContextUtil.hasButtonAuthorityCurrentUser(menuCode)) {
      return ""; //页面保存按钮当button标签里没有内容的时候
    } else {
      if (null != params.get("returnTag") && "false".equals(params.get("returnTag").toString())) {
        return Boolean.FALSE.toString();
      }
      String labelKey = "";
      if (params.get("labelKey") != null) {
        labelKey = params.get("labelKey").toString();//按钮名称国际化key
      }
      String defalutName = "";
      if (params.get("defalutName") != null) {
        defalutName = params.get("defalutName").toString();//默认的按钮名称
      }
      String language = SecurityContextUtil.getLanguageCode();
      String noright = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),language, "noright.C");
      if (!StringUtils.isBlank(labelKey)) {
        StringBuilder sb = new StringBuilder("");
        String[] keys = labelKey.split(SystemConstant.LABLE_SPLIT);
        for (String key : keys) {
          String content = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),language, key);
          if (!StringUtils.isBlank(content)) {
            sb.append(content);
            if (!language.equals(SystemConstant.LANGUAGE_CODE_ZH)) {
              sb.append(" ");
            }
          }
        }
        labelKey = sb.toString();
      }
      return "<li><a class='noright' target='noright' title='" + noright + "'><span style='color:#D8D1D1;'>"
          + (StringUtils.isBlank(labelKey) ? defalutName : labelKey) + "</span></a></li>";
    }
  }
}
